package main

import (
	"flag"
	"fmt"
	"net"

	"gitee.com/rocket049/gobstream"
)

func main() {
	flag.Parse()
	server := flag.Arg(0)
	if server == "" {
		server = "127.0.0.1"
	}
	conn, err := net.Dial("tcp", server+":9876")
	if err != nil {
		panic(err)
	}
	//defer conn.Close()
	stream := gobstream.NewStreamConn(conn)
	go printReplys(stream)
	go sendfile(stream, 8, "exam1.txt")
	go sendfile(stream, 9, "exam2.txt")
	stream.SendString(5, "Alone string: Hello.", false)
	stream.SendBytesHead(2, []byte("multi body message head\n"), true)
	stream.SendBytesBody(2, []byte("body 1\n"), false)
	stream.SendBytesBody(2, []byte("body 2\n"), false)
	stream.SendBytesBody(2, []byte("body 3\n"), false)
	stream.SendBytesEnd(2)
	var s string
	fmt.Scanln(&s)
	println("exit with:" + s)
	stream.Close()
}

func sendfile(stream *gobstream.StreamConn, session uint32, name string) {
	err := stream.SendFile(session, name)
	if err != nil {
		panic(err)
	} else {
		fmt.Printf("send file %v ok.\n", name)
	}
}

func printReplys(stream *gobstream.StreamConn) {
	for {
		data, err := stream.Recv()
		if err != nil {
			panic(err)
		}
		s, err := data.GetString()
		if err != nil {
			panic(err)
		}
		println(s)
	}
}
